/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.whxd.smarthome.api.rest;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Validator;

import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.hsview.client.HsviewClient;
import com.hsview.client.HsviewResponse;
import com.hsview.client.api.civil.user.GetAccessToken;
import com.whxd.framework.common.dto.ReturnObject;
import com.whxd.framework.common.exception.BusinessException;
import com.whxd.framework.security.SecurityUtils;
import com.whxd.framework.utils.BeanMapper;
import com.whxd.smarthome.Config;
import com.whxd.smarthome.api.rest.dto.GetAccessTokenResponseDto;
import com.whxd.smarthome.api.rest.dto.UserDto;
import com.whxd.smarthome.util.MediaTypes;
import com.whxd.system.user.entity.User;
import com.whxd.system.user.service.UserService;

/**
 * 用户管理的Restful API的Controller.
 * 
 * @author 张世鹏
 */
@RestController
@RequestMapping(value = "/api/v1/dh/user")
public class DhUserRestController {

	private static Logger logger = LoggerFactory.getLogger(DhUserRestController.class);

	@Autowired
	private UserService userService;

	@Autowired
	private Validator validator;

	/**
	 * 在系统中注册用户，并且将用户添加到乐橙平台中
	 * 
	 * @param dto
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
	@ResponseBody
	public ReturnObject register(@RequestBody UserDto dto) {
		logger.info("Register request data:" + dto);

		ReturnObject ro = new ReturnObject();
		try {
			User user = BeanMapper.map(dto, User.class);
			user = userService.register(user);
			UserDto result = BeanMapper.map(user, UserDto.class);

			ro.setSuccess(true);
			ro.setObj(result);
		} catch (BusinessException e) {
			ro.setSuccess(false);
			ro.setMsg(e.getMessage());
		}

		return ro;
	}

	@RequestMapping(value = "/getAccessToken", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
	@ResponseBody
	public ReturnObject getAccessToken(HttpServletResponse response) {

		HsviewClient m_client = new HsviewClient();
		m_client.setHost(Config.host);
		m_client.setAuth(Config.devUser, Config.devPassword);

		GetAccessToken req = new GetAccessToken();
		req.data.username = SecurityUtils.getCurrentSecurityUser().getUsername();
		logger.info("GetAccessToken request data:" + req.data.username);

		GetAccessToken.Response resp = (GetAccessToken.Response) m_client.request(req, 30000);

		if (resp == null) {
			logger.error("调用UnbindDevice接口时发生未知发错");
			return new ReturnObject(false, "发生未知发错");
		}
		
		logger.info("GetAccessToken response data:" + resp.getBody());

		ReturnObject ro = new ReturnObject();
		if (resp.getCode() == HttpStatus.SC_OK) {
			if (resp.getApiRetCode() == HsviewResponse.API_SUCCESS) {

				ro.setSuccess(true);
				ro.setMsg("[" + resp.getApiRetCode() + "] " + resp.getApiRetDesc());
				ro.setObj(new GetAccessTokenResponseDto(resp.data.accessToken, resp.data.expires));

			} else {
				ro.setSuccess(false);
				ro.setMsg("[" + resp.getApiRetCode() + "] " + resp.getApiRetDesc());
				logger.warn("[" + resp.getApiRetCode() + "] " + resp.getApiRetDesc());
			}
		} else {
			ro.setSuccess(false);
			ro.setMsg("[" + resp.getCode() + "] " + resp.getDesc());
			logger.error("[" + resp.getApiRetCode() + "] " + resp.getApiRetDesc());
		}

		return ro;
	}


}
